package com.cll.prototype.captcha.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cll.prototype.captcha.controller.service.email.SendEmailLogControllerFeignClient;
import com.cll.prototype.common.captcha.entity.AuthCaptcha;
import com.cll.prototype.common.captcha.mapper.AuthCaptchaMapper;
import com.cll.prototype.common.captcha.service.IAuthCaptchaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cll.prototype.common.dto.AjaxResult;
import com.cll.prototype.common.util.RandomUtils;
import com.cll.prototype.common.util.ValidateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 验证码服务的表 服务实现类
 * </p>
 *
 * @author CLL
 * @since 2020-10-26
 */
@Service
public class AuthCaptchaServiceImpl extends ServiceImpl<AuthCaptchaMapper, AuthCaptcha> implements IAuthCaptchaService {

    private static final Logger logger = LoggerFactory.getLogger(AuthCaptchaServiceImpl.class);


    @Qualifier(value = "sendEmailLogControllerFeignClient")
    @Autowired
    private SendEmailLogControllerFeignClient sendEmailLogControllerFeignClient;

    @Override
    public AjaxResult createRegisterCaptchaAndSendEmail(String email) {
        logger.info("===>>> 验证码服务开始生成验证码");
        // 1.检验邮箱合法性
        boolean checkEmailAddress = ValidateUtils.checkEmailAddress(email);
        if (!checkEmailAddress){
            return AjaxResult.error(45, "邮箱不合法");
        }
        // 2.检测验证码获取频率。必须间隔大于1分钟
        AuthCaptcha last = getOne(Wrappers.<AuthCaptcha>lambdaQuery()
                .eq(AuthCaptcha::getSubject, email)
                .eq(AuthCaptcha::getSubjectType, 1)
                .eq(AuthCaptcha::getType, 1)
                .orderByDesc(AuthCaptcha::getGmtCreate)
                .last("limit 1"));
        if (null != last && LocalDateTime.now().isBefore(last.getGmtCreate().plusMinutes(1))) {
            return AjaxResult.error(46, "一分钟只能获取一次注册验证码");
        }
        // 3.生成验证码
        String captcha = RandomUtils.getRandomStr2(6);

        AuthCaptcha authCaptcha = new AuthCaptcha();
        authCaptcha.setCaptcha(captcha);
        authCaptcha.setSubject(email);
        authCaptcha.setSubjectType(1);
        authCaptcha.setType(1);
        LocalDateTime now = LocalDateTime.now();
        authCaptcha.setGmtCreate(now);
        authCaptcha.setGmtExpire(now.plusMinutes(10));
        // 4.存储数据库
        boolean save = save(authCaptcha);
        if (save) {
            // 5.发送邮件
            return sendEmailLogControllerFeignClient.sendEmailCaptcha(email, captcha);
        }
        return AjaxResult.error(51, "生成注册验证码失败");
    }

    @Override
    public AjaxResult checkCaptcha(String email, String captcha) {
        if (StringUtils.isAnyBlank(email, captcha)) {
            return AjaxResult.error(41, "参数不合法");
        }
        // 1.检测邮箱号是否合法
        boolean emailAddress = ValidateUtils.checkEmailAddress(email);
        if (emailAddress) {
            AuthCaptcha last = getOne(Wrappers.<AuthCaptcha>lambdaQuery()
                    .eq(AuthCaptcha::getSubject, email)
                    .eq(AuthCaptcha::getSubjectType, 1)
                    .eq(AuthCaptcha::getType, 1)
                    .orderByDesc(AuthCaptcha::getGmtCreate)
                    .last("limit 1"));

            if (null == last) {
                return AjaxResult.error(44, "请先获取验证码");
            }

            if (LocalDateTime.now().isAfter(last.getGmtExpire())) {
                return AjaxResult.error(43, "验证码已过有效期，请重新获取");
            }

            if (!captcha.equals(last.getCaptcha())) {
                return AjaxResult.error(45, "验证码不正确");
            }

            return AjaxResult.success(20, "校验通过", 1);
        }
        return AjaxResult.error(42, "邮箱号码不合法");
    }
}
